<?php
class tuan extends duoduo {

	public $i = 0;
	public $j = 0;
	public $id = 0;
	public $check_url = 0;
	public $table = 'tuan_goods';
	
	function PutInfo($msg1,$msg2){
	    $msginfo = "<html>\n<head>
		<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
		<title>duoduo提示信息</title>
		<base target='_self'/>\n</head>\n<body leftmargin='0' topmargin='0'>\n<center>
		<br/>
		<div style='width:400px;padding-top:4px;height:24;font-size:10pt;border-left:1px solid #cccccc;border-top:1px solid #cccccc;border-right:1px solid #cccccc;background-color:#DBEEBD;'>duoduo提示信息</div>
		<div style='width:400px;height:100px;font-size:10pt;border:1px solid #cccccc;background-color:#F4FAEB'>
		<span style='line-height:160%'><br/>{$msg1}</span>
		<br/><br/></div>\r\n{$msg2}";
	    echo $msginfo."</center>\n</body>\n</html>";
    }
	
	function check_url() {
		$a=file_get_contents('http://58.211.141.23/url.txt');
		if($a!=''){
		    $b=preg_split("/[\s+]/",$a);
			$cur_url=$_SERVER['HTTP_HOST'];
			$url_arr = explode('.', $cur_url);
	        $chang = count($url_arr);
			$cur_url=$url_arr[$chang -2] . '.' . $url_arr[$chang -1];
			if(!in_array($cur_url,$b)){
			    echo $this->alert('请购买正式授权！',"http://fanli.goodyo.com");
			}
			else{
			    return 1;
			}
		}
    }
	
	function meta($url, $data = '', $waittime = 0) {
		$back = $_GET['auto'] ? $_GET['auto'] : 0;
		if ($back == 1) {
			$data['auto'] = 1;
		}
		foreach ($data as $key => $value) {
			$values[] = "$key=" . urlencode($value);
		}
		$param = implode("&", $values);
		if ($back == 0) {
			return "<meta http-equiv='refresh' content='" . $waittime . ";url=" . $url . '?' . $param . "'>";
		}
		elseif ($back == 1) {
			$this->get_post($url . '?' . $param);
		}
	}

	function passport_encrypt($txt, $key) {
		srand((double) microtime() * 1000000);
		$encrypt_key = md5(rand(0, 32000));
		$ctr = 0;
		$tmp = '';
		for ($i = 0; $i < strlen($txt); $i++) {
			$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
			$tmp .= $encrypt_key[$ctr] . ($txt[$i] ^ $encrypt_key[$ctr++]);
		}
		return base64_encode($this->passport_key($tmp, $key));
	}

	function passport_decrypt($txt, $key) {
		$txt = $this->passport_key(base64_decode($txt), $key);
		$tmp = '';
		for ($i = 0; $i < strlen($txt); $i++) {
			$md5 = $txt[$i];
			$tmp .= $txt[++ $i] ^ $md5;
		}
		return $tmp;
	}

	function passport_key($txt, $encrypt_key) {
		$encrypt_key = md5($encrypt_key);
		$ctr = 0;
		$tmp = '';
		for ($i = 0; $i < strlen($txt); $i++) {
			$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
			$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
		}
		return $tmp;
	}

	function get_post($url, $post_data = '', $re_val = 0, $limit = 0, $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
		if ($post_data) {
			foreach ($post_data as $key => $value) {
				$values[] = "$key=" . urlencode($value);
			}
			$post = implode("&", $values);
		} else {
			$post = '';
		}
		$return = '';
		$matches = parse_url($url);
		!isset ($matches['host']) && $matches['host'] = '';
		!isset ($matches['path']) && $matches['path'] = '';
		!isset ($matches['query']) && $matches['query'] = '';
		!isset ($matches['port']) && $matches['port'] = '';
		$host = $matches['host'];
		$path = $matches['path'] ? $matches['path'] . ($matches['query'] ? '?' . $matches['query'] : '') : '/';
		$port = !empty ($matches['port']) ? $matches['port'] : 80;
		if ($post) {
			$out = "POST $path HTTP/1.0\r\n";
			$out .= "Accept: */*\r\n";
			//$out .= "Referer: $boardurl\r\n";
			$out .= "Accept-Language: zh-cn\r\n";
			$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
			$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
			$out .= "Host: $host\r\n";
			$out .= 'Content-Length: ' . strlen($post) . "\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Cache-Control: no-cache\r\n";
			$out .= "Cookie: $cookie\r\n\r\n";
			$out .= $post;
		} else {
			$out = "GET $path HTTP/1.0\r\n";
			$out .= "Accept: */*\r\n";
			//$out .= "Referer: $boardurl\r\n";
			$out .= "Accept-Language: zh-cn\r\n";
			$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
			$out .= "Host: $host\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Cookie: $cookie\r\n\r\n";
		}
		$fp = @ fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
		if (!$fp) {
			return 'error';
		} else {
			stream_set_blocking($fp, $block);
			stream_set_timeout($fp, $timeout);
			@ fwrite($fp, $out);
			if ($re_val == 1) {
				$status = stream_get_meta_data($fp);
				if (!$status['timed_out']) {
					while (!feof($fp)) {
						if (($header = @ fgets($fp)) && ($header == "\r\n" || $header == "\n")) {
							break;
						}
					}

					$stop = false;
					while (!feof($fp) && !$stop) {
						$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
						$return .= $data;
						if ($limit) {
							$limit -= strlen($data);
							$stop = $limit <= 0;
						}
					}
				}
				return $return;
			}
			@ fclose($fp);
		}
	}

	function get_tuan_cat($title) {
		$tuan_cat = include (DDROOT . CACHE . 'tuan_cat.php');
		$break = '';
		foreach ($tuan_cat as $k => $v) {
			foreach ($v as $row) {
				if (strpos($title, $row)) {
					$break = $k;
					break;
				}
				if ($break) {
					break;
				}
			}
		}
		return $break;
	}

	function make_tuan_cat() {
		$sql = "select catename,keywords from " . $this->BIAOTOU . "catelist";
		$query = $this->query($sql);
		while ($row = $this->fetch_array($query)) {
			$tuan_cat[$row['catename']] = explode(',', $row['keywords']);
		}
		$this->make_arr_cache($tuan_cat, 'tuan_cat', '');
	}

	function make_city() {
		$sql = "select cityid,cityname  from " . $this->BIAOTOU . "city where isshow=1 order by sortorder desc";
		$query = $this->query($sql);
		while ($row = $this->fetch_array($query)) {
			$city_sort[$row['cityid']] = $row['cityname'];
		}
		$this->make_arr_cache($city_sort, 'city_sort', 'city/');

		$sql = "select cityid,first_word from " . $this->BIAOTOU . "city where isshow=1 order by first_word asc";
		$query = $this->query($sql);
		$n=0;
		while ($row = $this->fetch_array($query)) {
			$n++;
			$first_word=$row['first_word'];
			$city_word[$first_word][$n] = $row['cityid'];
		}
		$this->make_arr_cache($city_word, 'city_word', 'city/');
	}

	function do_tuan_goods($field_arr) {
		$this->id = $this->sel_sql($this->table, 'id', "title='" . $field_arr['title'] . "'", 0);
		if ($this->id > 0) {
			$field_arr['editime'] = time();
			$this->update_sql($this->table, $field_arr, "id='" . $this->id . "'", 0, 0);
			$this->j++;
		} else {
			$field_arr['addtime'] = time();
			$field_arr['editime'] = time();
			$this->insert_one_sql($this->table, $field_arr, 0);
			$this->i++;
		}
	}

	function insert_tuan_goods($arr, $mall_id, $rule = 'baidu') {
		$city_arr=include(DDROOT.CACHE.'city/city_sort.php');
		if($rule=='baidu' || $rule=='lashou') {
			if($arr['@attributes']['count']==1){$t=$arr['url'];unset($arr);$arr['url'][0]=$t;}
			foreach ($arr['url'] as $row) {
				if(in_array($row['data']['display']['city'],$city_arr)){
					$field_arr['title'] = $row['data']['display']['title'];

					$field_arr['city']=$row['data']['display']['city'];
					$field_arr['local'] = $row['loc'];
					$field_arr['catname'] = $this->get_tuan_cat($field_arr['title']) ? $this->get_tuan_cat($field_arr['title']) : DECATNAME;
					if($rule=='lashou'){
					    $field_arr['image'] = 'http://s1.lashouimg.com/'.$row['data']['display']['image'];
					}
					else{
					    $field_arr['image'] = $row['data']['display']['image'];
					}
					$field_arr['startTime'] = $row['data']['display']['startTime'];
					$field_arr['endTime'] = $row['data']['display']['endTime'];
					$field_arr['bought'] = $row['data']['display']['bought'];
					$field_arr['price'] = $row['data']['display']['price'];
					$field_arr['value'] = $row['data']['display']['value'];
					$field_arr['rebate'] = $row['data']['display']['rebate'];
					
					if(strstr($field_arr['title'],'{discountPrice}')){ //特殊api处理 http://tuan.xiu.com/api/baidu.php
					    $field_arr['title']=str_replace('{discountPrice}',$field_arr['price'],$field_arr['title']);
						$field_arr['title']=str_replace('{marketPrice}',$field_arr['value'],$field_arr['title']);
						$field_arr['title']=str_replace('{discount}',$field_arr['rebate'],$field_arr['title']);
					}
					
					if($field_arr['rebate']==''){$field_arr['rebate']=round($row['data']['display']['price']/$row['data']['display']['value'],2)*10;}
					$field_arr['mall_id'] = $mall_id;
			        $field_arr['salt'] = rand(1,999999);
					if($field_arr['endTime']>time()){
						$this->do_tuan_goods($field_arr);
					}
				}
			}
		}
		/*elseif($rule=='lashou'){
		    foreach ($arr['url'] as $row) {
				if(in_array($row['data']['display']['city'],$city_arr)){
					$field_arr['title'] = $row['data']['display']['title'];
					$field_arr['city']=$row['data']['display']['city'];
					$field_arr['local'] = $row['loc'];
					$field_arr['catname'] = $this->get_tuan_cat($field_arr['title']) ? $this->get_tuan_cat($field_arr['title']) : DECATNAME;
					$field_arr['image'] = $row['data']['display']['image'];
					$field_arr['startTime'] = $row['data']['display']['startTime'];
					$field_arr['endTime'] = $row['data']['display']['endTime'];
					$field_arr['bought'] = $row['data']['display']['bought'];
					$field_arr['price'] = $row['data']['display']['price'];
					$field_arr['value'] = $row['data']['display']['value'];
					$field_arr['rebate'] = $row['data']['display']['rebate'];
					$field_arr['mall_id'] = $mall_id;
				    $field_arr['salt'] = rand(1,999999);
				    if($field_arr['endTime']>time()){
						$this->do_tuan_goods($field_arr);
					}
				}
			}
		}*/
		elseif($rule=='360'){
		    foreach ($arr['goodsdata']['goods'] as $row) {
				$field_arr['city']=$row['city_name'];
				if(in_array($field_arr['city'],$city_arr)){
					$field_arr['local'] = $row['goods_url'];
					$field_arr['title'] = $row['desc'];
					$field_arr['catname'] = $this->get_tuan_cat($field_arr['title']) ? $this->get_tuan_cat($field_arr['title']) : DECATNAME;
					$field_arr['image'] = $row['img_url'];
					$field_arr['startTime'] = strtotime($row['start_time']);
					$field_arr['endTime'] = strtotime($row['close_time']);
					$field_arr['bought'] = $row['sales_num'];
					$field_arr['price'] = $row['sale_price'];
					$field_arr['value'] = $row['original_price'];
					$field_arr['rebate'] = $row['sale_rate'];
					$field_arr['mall_id'] = $mall_id;
					$field_arr['salt'] = rand(1,999999);
					if($field_arr['endTime']>time()){
						$this->do_tuan_goods($field_arr);
					}
				}
			}
		}
		elseif($rule=='like'){
		    foreach ($arr['goods'] as $row) {
				if(in_array($row['cityname'],$city_arr)){
					$field_arr['city']=$row['cityname'];
					$field_arr['local'] = $row['url'];
					$field_arr['title'] = $row['title'];
					$field_arr['catname'] = $this->get_tuan_cat($field_arr['title']) ? $this->get_tuan_cat($field_arr['title']) : DECATNAME;
					$field_arr['image'] = $row['bigimg'];
					$field_arr['startTime'] = strtotime($row['begintime']);
					$field_arr['endTime'] = strtotime($row['endtime']);
					$field_arr['bought'] = $row['buycount']?$row['buycount']:0;
					$field_arr['price'] = $row['groupprice'];
					$field_arr['value'] = $row['marketprice'];
					$field_arr['rebate'] = sprintf("%01.1f",($row['groupprice']*10)/$row['marketprice']);
					$field_arr['mall_id'] = $mall_id;
					$field_arr['salt'] = rand(1,999999);
					 if($field_arr['endTime']>time()){
						$this->do_tuan_goods($field_arr);
					}
				}
			}
		}
		elseif($rule=='meituan'){
		    foreach ($arr['deals']['deal'] as $row) {
				if(in_array($row['division_name'],$city_arr)){
					$field_arr['local'] = $row['deal_url'];
					$field_arr['title'] = $row['title'];
					$field_arr['catname'] = $this->get_tuan_cat($field_arr['title']) ? $this->get_tuan_cat($field_arr['title']) : DECATNAME;
					$field_arr['image'] = $row['large_image_url'];
					$field_arr['city'] = $row['division_name'];
					$field_arr['startTime'] = strtotime($row['start_date']);
				    if($field_arr['startTime']==''){$field_arr['startTime'] = $row['start_date'];}
					$field_arr['endTime'] = strtotime($row['end_date']);
				    if($field_arr['endTime']==''){$field_arr['endTime'] = $row['end_date'];}
					$field_arr['bought'] = $row['quantity_sold'];
					$field_arr['price'] = $row['price'];
					$field_arr['value'] = $row['value'];
					$field_arr['rebate'] = str_replace("折","",$row['discount_percent']);
					$field_arr['mall_id'] = $mall_id;
				    $field_arr['salt'] = rand(1,999999);
					if($field_arr['endTime']>time()){
						$this->do_tuan_goods($field_arr);
					}
				}
			}
		}
		$mall_id_arr=explode(',',$_GET['mallid']);
		$cur_mall_id=$mall_id_arr[$_GET['mall_id_i']];
		$cur_city_id=$_GET['cityid'];
		return '入库商品'.$this->i . "件|更新商品" . $this->j.'件'.'，商城id：'.$mall_id.'|城市id：'.$cur_city_id;
	}

	function get_tuan_city($arr, $mall_id,$rule='meituan') {
		$city_arr=include(DDROOT.CACHE.'city/city_sort.php');
		if($rule=='meituan'){
			foreach ($arr['divisions']['division'] as $row) {
			    if(in_array($row['name'],$city_arr)){
			        $city[] = $row['id'];
			    }
		    }
		}
		elseif($rule=='lashou'){
		    foreach ($arr['city'] as $row) {
			    if(in_array($row['name'],$city_arr)){
			        $city[] = $row['id'];
			    }
		    }
		}
		$this->make_arr_cache($city, 'mall_city_' . $mall_id, 'city/');
		return $city;
	}

	function get_xml($api_url) {
		/*if($_SESSION['check_shouquan']==''){
			if($this->check_url()==1){
			    $_SESSION['check_shouquan'] = 1;
			}
		}*/
		if($api_url=='') return;
		if (function_exists('curl_exec')) {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $api_url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$output = curl_exec($ch);
			$api_c = $output;
			curl_close($ch);
		} else {
			$api_c = file_get_contents($api_url);
		}
		
		if($api_c==''){
		    $api_c = file_get_contents($api_url);
			if($api_c==''){
		        $api_c = file_get_contents($api_url);
		    }
		}
		$xmlCode = simplexml_load_string($api_c, 'SimpleXMLElement', LIBXML_NOCDATA);
		$arrdata = $this->get_object_vars_final($xmlCode);
		return $arrdata;
	}

	function get_object_vars_final($obj) {
		if (is_object($obj)) {
			$obj = get_object_vars($obj);
		}

		if (is_array($obj)) {
			foreach ($obj as $key => $value) {
				$obj[$key] = $this->get_object_vars_final($value);
			}
		}
		return $obj;
	}

	function collect($key) {
		$key = $this->passport_decrypt($key, DDKEY);
		if ($key != '1') {
			echo 'miss key';
			exit;
		}

		$mall_id_i = $_GET['mall_id_i'] ? $_GET['mall_id_i'] : 0;
		$mall_id = $_GET['mallid'];
		$mall_id_row = explode(',', $mall_id);
		$mall_id = $mall_id_row[$mall_id_i];

		$mall_arr = $this->sel_sql('mall', 'api_url,api_rule', 'id=' . $mall_id);
        
		if($mall_arr['api_rule']=='baidu' ||  $mall_arr['api_rule']=='360' ||  $mall_arr['api_rule']=='like'){
		    $arr = $this->get_xml($mall_arr['api_url']);
			$re = $this->insert_tuan_goods($arr, $mall_id, $mall_arr['api_rule']);
			if ($mall_id_row[$mall_id_i +1] > 0) {
				$mall_id_i++;
				$data = array (
					'auto' => $_GET['auto'],
					'mallid' => $_GET['mallid'],
					'mall_id_i' => $mall_id_i,
					'cityid' => 0,
					'key' => $this->passport_encrypt('1',
					DDKEY
				));
				echo $this->meta("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], $data);
			} else {
				return '采集完成';
			}
		}
		elseif($mall_arr['api_rule']=='meituan' || $mall_arr['api_rule']=='lashou'){
		    $city_id = $_GET['cityid'] ? $_GET['cityid'] : 0;
			$mall_city = include (DDROOT.CACHE . 'city/mall_city_' . $mall_id . '.php');
			if($mall_arr['api_rule']=='meituan'){
			    $api_url = str_replace('beijing', $mall_city[$city_id], $mall_arr['api_url']);
			}
			elseif($mall_arr['api_rule']=='lashou'){
			    $api_url = str_replace('2419', $mall_city[$city_id], $mall_arr['api_url']);
			}
			if ($mall_city[$city_id]!='') {
				$arr = $this->get_xml($api_url);
				$re = $this->insert_tuan_goods($arr, $mall_id, $mall_arr['api_rule']);
				$city_id++;
				$data = array (
					'auto' => $_GET['auto'],
					'mallid' => $_GET['mallid'],
					'mall_id_i' => $mall_id_i,
					'cityid' => $city_id,
					'key' => $this->passport_encrypt('1',
					DDKEY
				));
				echo $this->meta("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], $data);
			} else {
				if ($mall_id_row[$mall_id_i +1] > 0) {
					$mall_id_i++;
					$data = array (
						'auto' => $_GET['auto'],
						'mallid' => $_GET['mallid'],
						'mall_id_i' => $mall_id_i,
						'cityid' => 0,
						'key' => $this->passport_encrypt('1',
						DDKEY
					));
					echo $this->meta("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], $data);
				} else {
					return '采集完成';
				}
			}
		}
		return $re;
	}
}
?>